package com.by.service.sys.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.by.common.bean.PageBean;
import com.by.common.crud.BaseServiceImpl;
import com.by.entity.sys.Dict;
import com.by.mapper.sys.DictMapper;
import com.by.service.sys.DictService;
import com.by.utils.AssertsUtils;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DictServiceImpl extends BaseServiceImpl<DictMapper, Dict> implements DictService {

    @Override
    public List queryType() {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "dictType", "name")
                .isNull("pid");
        return baseMapper.selectList(queryWrapper);
    }


    @Override
    public PageBean query(Map map) {
        int pageNum = 1, pageSize = 10;
        if (null != map) {
            if (map.containsKey("pageNum")) {
                pageNum = Integer.parseInt(map.get("pageNum").toString());
            }
            if (map.containsKey("pageSize")) {
                pageSize = Integer.parseInt(map.get("pageSize").toString());
            }
        }

        IPage<Dict> page = new Page(pageNum, pageSize);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("pid", map.get("pid"));
        queryWrapper.orderByAsc("sorts");
        page = baseMapper.selectPage(page, queryWrapper);

        return new PageBean(page.getCurrent(), page.getSize(), page.getTotal(), page.getRecords());
    }


    @Override
    public int delete(Serializable id) {
        //先删除父id为  给定id的字典数据
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("pid", id);
        baseMapper.delete(wrapper);
        return super.delete(id);
    }

    @Override
    public List queryDictByType(String type) {
        return baseMapper.queryDictByType(type);
    }


    @Override
    public Map queryDictByTypes(String types) {
        AssertsUtils.isNull(types,"字典类型不能为空！");
        Map map = new HashMap();
        //分隔类型
        String[] type = types.split(",");
        for (String t : type) {
            List list = baseMapper.queryDictByType(t);
            map.put(t, list);
        }
        return map;
    }
}
